<template>
  <el-dialog v-model="dialogVisible" title="编辑分类">
    <el-form :model="form" label-width="120px">
      <el-form-item label="分类名称">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'

interface Form {
  id?: number | null
  name: string
}

const props = defineProps<{
  modelValue: boolean
  initialValues: Form
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'submit', value: Form): void
}>()

const dialogVisible = ref(props.modelValue)
const form = ref<Form>({ ...props.initialValues })

const submitForm = () => {
  emit('submit', form.value)
  dialogVisible.value = false
}

watch(() => props.modelValue, (newVal) => {
  dialogVisible.value = newVal
  if (newVal) {
    form.value = { ...props.initialValues }
  }
})
</script>